package amazon

import (
	"black_mamba/global"
	"black_mamba/pages"
	"black_mamba/workers"
	_ "embed"
	"fmt"
	"gitee.com/wengo/windows_gui/wapi"
	"gitee.com/wengo/windows_gui/widget"
	"gitee.com/wengo/windows_gui/xc"
	"gitee.com/wengo/windows_gui/xcc"
	_ "github.com/go-sql-driver/mysql"
	"github.com/tidwall/gjson"
	"strconv"
	"sync"
	"time"
	"unsafe"
)

type CouponPage struct {
	pages.Foundation
	style        map[string]int
	taskTotal    *widget.ShapeText
	detailLayout *widget.LayoutEle
}

func NewCouponPage() *CouponPage {
	couponPage := &CouponPage{
		Foundation: pages.Foundation{
			ExecuteBtn: widget.NewButtonByName("couponExecuteBtn"),
			LogEdit:    widget.NewEditByName("couponLogEdit"),
			Style:      nil,
			Topic:      "coupon",
			//ListBoxLayout: widget.NewLayoutEleByName("couponListBoxLayout"),
			//ParentLayout:  widget.NewLayoutEleByName("couponParentLayout"),
		},
		taskTotal: widget.NewShapeTextByName("couponTaskTotal"),
	}

	// 绑定执行按钮事件
	couponPage.ExecuteBtn.Event_BnClick(couponPage.execute)

	// 设置log样式
	couponPage.SetEditStyle()

	// 创建listbox
	couponPage.NewListBox("couponListBox", "coupon_list.xml")

	//绑定所有订阅
	//绑定所有订阅
	couponPage.Subscribes()
	couponPage.customSubscribes()

	// 设置listbox的按钮事件
	couponPage.ListBox.RegEventC(xcc.XE_LISTBOX_TEMP_CREATE_END, func(pItem *xc.ListBox_Item_, nFlag int, pbHandled *bool) int {
		itemViewBtn := widget.NewButtonByHandle(couponPage.ListBox.GetTemplateObject(int(pItem.Index), 1))
		itemViewBtn.Event_BnClick(func(pbHandled *bool) int {
			index := couponPage.ListBox.GetItemIndexFromHXCGUI(itemViewBtn.Handle)
			asin := couponPage.ListBox.GetItemText(index, 1)
			wapi.ShellExecuteW(1, "open", `C:\Program Files\Google\Chrome\Application\chrome.exe`, fmt.Sprintf("https://www.amazon.com/dp/%s", asin), "", 3)
			return 0
		})
		return 0
	})
	return couponPage
}

//注册所有订阅者
func (b *CouponPage) customSubscribes() {
	//订阅任务总数
	updateTaskTotal := b.updateTaskTotal
	_ = global.BM_EVENTBUS.Subscribe(fmt.Sprintf("%s:taskTotal", b.Topic), func(data map[string]int) {
		xc.XC_CallUiThread(updateTaskTotal, int(uintptr(unsafe.Pointer(&data))))
	})

	//订阅任务反馈
	updateFeedBack := b.updateFeedBack
	_ = global.BM_EVENTBUS.Subscribe(fmt.Sprintf("%s:feedback", b.Topic), func(data map[interface{}]uint) {
		xc.XC_CallUiThread(updateFeedBack, int(uintptr(unsafe.Pointer(&data))))
	})

}

/* 事件回调 */
func (b *CouponPage) execute(pbHandled *bool) int {
	*pbHandled = true

	if global.BM_CONFIG.Section("basic").Key("serialNumberCiphertext").Value() == "" {
		b.UpdateLog(int(uintptr(unsafe.Pointer(&(map[string]string{"status": "error", "content": "请先设置机器序列号"})))))
		return 0
	}

	if global.BM_CONFIG.Section("proxy").Key("username").Value() == "" {
		b.UpdateLog(int(uintptr(unsafe.Pointer(&(map[string]string{"status": "error", "content": "请先设置代理用户名"})))))
		return 0
	}

	if global.BM_CONFIG.Section("proxy").Key("password").Value() == "" {
		b.UpdateLog(int(uintptr(unsafe.Pointer(&(map[string]string{"status": "error", "content": "请先设置代理密码"})))))
		return 0
	}

	//重绘父
	b.ToggleBtn(int(uintptr(unsafe.Pointer(b.ExecuteBtn))))

	go func() {

		tableData := map[string]interface{}{
			"headers": []string{"id", "asin", "seller_id", "total"},
			"body":    []map[string]string{},
		}

		for global.BM_POOL.Running() < 5 {

			// 获取任务
			//data := global.BM_API.GetTaskList(global.BM_CONFIG.Section("basic").Key("serialNumberCiphertext").Value(), "4.8", false) // 美国
			data := `{"status":"success","data":{"machine":{"machine_id":{"title":"»úÆ÷ID","value":"vps.ueuz.com:55404","type":"input"},"executeTimeout":{"title":"×î³¤Ê±¼ä(·Ö)","value":"1","type":"input"},"privacy":{"close_image":{"title":"¹Ø±ÕÍ¼Æ¬","value":"true","type":"checkbox"},"close_flash":{"title":"¹Ø±ÕFlash","value":"true","type":"checkbox"}},"speed":{"title":"ä¯ÀÀËÙ¶È","value":"0.5","type":"input"},"executeMethod":{"title":"Ö´ÐÐÄ£Ê½","value":"http_method","type":"radio"},"browse":{"title":"ä¯ÀÀÆ÷","value":"chrome","type":"radio"},"proxyType":{"title":"´úÀíÀàÐÍ","value":"vpn","type":"radio"},"proxy_address":{"title":"´úÀíµØÖ·","value":"","type":"input"},"timeout":{"title":"·¢°ü³¬Ê±Ê±¼ä","value":"60","type":"input"},"concurrent":{"title":"²¢·¢·¢°üÊý","value":"5","type":"input"},"machineTypeGroup":{"title":"»úÆ÷ÀàÐÍ×é","value":1,"type":"select"},"machineType":{"title":"ÈÎÎñÀàÐÍ","value":2,"type":"select"}},"tasks":[{"task_group_name":"×é1","list":[{"task_id":{"title":"ÈÎÎñID","value":"6929"},"task_group_id":{"title":"ÈÎÎñ×éID","value":"6929"},"name":{"title":"ÈÎÎñÃû","value":"ÀîË§5.2¸ß¶û·òÍÆ¸Ë"},"task_group_name":{"title":"ÈÎÎñ×éÃû","value":"ÀîË§5.2¸ß¶û·òÍÆ¸Ë"},"task_delay":{"title":"ÑÓ³ÙÖ´ÐÐ(·ÖÖÓ)","value":"0"},"success":{"title":"³É¹¦Êý","value":"0"},"target":{"title":"Ä¿±êÊý","value":"10000"},"asin":{"title":"ASIN","value":"B09XHMGRC5"},"keywords":{"title":"¹Ø¼ü´Ê","value":"B0B79JK24J"},"seller_id":{"title":"Seller ID","value":"A2TPU523YC9RHN"},"category_name":{"title":"·ÖÀàÃû³Æ","value":"AZWRYG4A5FSSR"},"product_name":{"title":"²úÆ·Ãû","value":"¸ß¶û·òÍÆ¸Ë"},"shopping_cart_rate":{"title":"¹ºÎï³µÂÊ","value":"100"},"wishlist_rate":{"title":"ÐÄÔ¸µ¥ÂÊ","value":"0"},"website":{"title":"Ä¿±êÍøÕ¾","value":"www.amazon.com"},"search_method":{"title":"ËÑË÷·½Ê½","value":"store"},"payment_method":{"title":"¸¶¿î·½Ê½","value":"credit_card"},"is_referrer":{"title":"ÉèÖÃÀ´Ô´","value":"false"},"code":{"title":"¹ú¼Ò´úºÅ","value":"us"},"lang_code":{"title":"ÓïÑÔ","value":"en-US"},"task_type":{"title":"ÈÎÎñÀàÐÍ","value":"login_add_cart_task"},"use_proxy":{"title":"Ê¹ÓÃ´úÀí","value":"false"},"concurrent_num":{"title":"concurrent_num","value":"5"},"register_method":{"title":"ÊÇ·ñ·¢°ü","value":"http"},"payment_type":{"title":"¸¶¿îÀàÐÍ","value":"no_payment"},"address_type":{"title":"µØÖ·Ñ¡Ïî","value":""},"creditcard_type":{"title":"ÐÅÓÃ¿¨Ñ¡Ïî","value":""},"is_check_cart":{"title":"¼ì²é¹ºÎï³µ","value":"false"},"account_type":{"title":"ÕË»§ÀàÐÍ","value":"login"},"page_range":{"title":"Ò³Âë·¶Î§","value":"20"},"click_ads":{"title":"µã»÷¹ã¸æ","value":""},"intelligent_page":{"title":"ÖÇÄÜÒ³Âë","value":""},"is_brand":{"title":"¿ªÆôÆ·ÅÆ","value":"false"},"brand_name":{"title":"Æ·ÅÆÃû³Æ","value":""},"qty":{"title":"¼Ó¹ºÊýÁ¿","value":"166"},"is_checkout":{"title":"ÊÇ·ñ¸¶¿î","value":"0"},"is_verify_account":{"title":"ÑéÖ¤ÕË»§","value":"0"},"is_check_review":{"title":"¼ì²éÆÀÂÛ","value":"0"},"is_check_review_then_quit":{"title":"¼ì²éÆÀÂÛºóÍË³ö","value":"false"},"is_check_stock":{"title":"¼ì²é¿â´æ","value":"0"},"related_asin_list":{"title":"¹ØÁªASINÁÐ±í","value":""},"blacklist":{"title":"ºÚÃûµ¥","value":""},"login_add_cart_task_list_id":{"title":"login_add_cart_task_list_id","value":"4JUdGzvrMFDWrUUwY3toJATSeNwjn54LkCnKBPRzDuhzi5vSepHfUckJNxRL2gjkNrSqtCoRUrEDAgRwsQvVCjZbRyFTLRNyDmT1a1boZVreview_comment":{"title":"ÁôÆÀÄÚÈÝ","value":""},"review_rating":{"title":"ÐÇ¼¶","value":""},"review_id":{"title":"ÆÀÂÛÄ£°åID","value":""},"review_images":{"title":"ÆÀÂÛÍ¼Æ¬","value":""}}]}],"account":{"name":{"title":"ÕÊ»§Ãû","value":"None"},"email":{"title":"ÓÊÏä","value":"None"},"password":{"title":"ÃÜÂë","value":"None"},"website":{"title":"Ä¿±êÍøÕ¾","value":"www.amazon.com"},"code":{"title":"¹ú¼Ò´úºÅ","value":"us"},"lang_code":{"title":"ÓïÑÔ","value":"en-US"},"cookie":{"title":"»º´æ","value":""}}}}`

			if gjson.Get(data, "status").String() != "success" {
				global.BM_EVENTBUS.Publish("coupon:log", map[string]string{"status": "info", "content": "暂无任务需要执行, 暂停1分钟再请求"})
				//xc.XC_CallUiThread(updateLog, int(uintptr(unsafe.Pointer(&(map[string]string{"status": "info", "content": "暂无任务需要执行, 暂停1分钟再请求"})))))
				time.Sleep(1 * time.Minute)
				continue
			}

			global.BM_EVENTBUS.Publish("coupon:clearLog")
			global.BM_EVENTBUS.Publish("coupon:log", map[string]string{"status": "success", "content": "成功获取任务"})
			global.BM_EVENTBUS.Publish("coupon:taskTotal", map[string]int{"taskGroupTotal": int(gjson.Get(data, "data.task_group_total.value").Int()), "taskTotal": int(gjson.Get(data, "data.task_total.value").Int())})

			delay := gjson.Get(data, "data.machine.executeTimeout.value").Int()
			//delay = 0
			var body []map[string]string
			for _, task := range gjson.Get(data, "data.tasks").Array() {
				for _, d := range gjson.Get(task.String(), "list").Array() {
					id := gjson.Get(d.String(), "task_id.value").String()
					asin := gjson.Get(d.String(), "asin.value").String()
					sellerId := gjson.Get(d.String(), "seller_id.value").String()
					body = append(body, map[string]string{
						"id":        id,
						"asin":      asin,
						"seller_id": sellerId,
					})
				}
			}

			tableData["body"] = body

			// 更新列表
			global.BM_EVENTBUS.Publish("coupon:updateTable", tableData)

			couponWorker := workers.NewCouponWorker()
			var taskWg sync.WaitGroup
			var chans []chan interface{}
			for _, task := range gjson.Get(data, "data.tasks").Array() {
				for i := 0; i <= 10; i++ {
					list := task.String()
					var ch = make(chan interface{})
					chans = append(chans, ch)
					err := global.BM_POOL.Submit(couponWorker.Decorator(couponWorker.Execute, map[string]interface{}{
						"tasks": list,
					}, &taskWg, ch))
					if err != nil {
						return
					}
				}

				//break
			}

			taskWg.Wait()

			global.BM_EVENTBUS.Publish("coupon:log", map[string]string{"status": "success", "content": "================ 开始统计 =================="})

			// 获取协程返回的数据
			for _, ch := range chans {
				chResult := <-ch
				if chResult != nil {
					result := chResult.(map[string]string)
					if len(result) > 0 {
						global.BM_EVENTBUS.Publish("coupon:log", result)
					}
				}
			}

			global.BM_EVENTBUS.Publish("coupon:log", map[string]string{"status": "success", "content": "================ 统计结束 =================="})
			global.BM_EVENTBUS.Publish("coupon:log", map[string]string{"status": "info", "content": fmt.Sprintf("等待 %d 分钟进行下一轮任务", delay)})

			time.Sleep(time.Duration(delay) * time.Minute)

		}

		xc.XC_CallUiThread(b.ToggleBtn, int(uintptr(unsafe.Pointer(b.ExecuteBtn))))

	}()

	return 0
}

func (b *CouponPage) updateTaskTotal(data int) int {
	result := *(*map[string]int)(unsafe.Pointer(uintptr(data)))
	b.taskTotal.SetText(fmt.Sprintf("当前任务组总数为: %d, 任务总数为: %d", result["taskGroupTotal"], result["taskTotal"]))
	b.taskTotal.Redraw()
	widget.NewLayoutEleByHandle(b.taskTotal.GetParentEle()).AdjustLayout(0)
	widget.NewLayoutEleByHandle(b.taskTotal.GetParentEle()).Redraw(true)

	return 0
}

func (b *CouponPage) updateFeedBack(feedback int) int {
	data := *(*map[interface{}]uint)(unsafe.Pointer(uintptr(feedback)))
	count := b.ListBox.GetCount_AD()
	if count > 0 {
		for iitem := 0; iitem < count; iitem++ {
			asin := b.ListBox.GetItemText(iitem, 1)
			val, ok := data[asin]
			if ok {
				curTotal, _ := strconv.Atoi(b.ListBox.GetItemText(iitem, 1))
				curTotal += int(val)
				xc.XAdTable_SetItemText(b.HAdapter, iitem, 3, strconv.Itoa(curTotal))
			}

		}
	}

	b.RedrawListBoxLayout()

	return 0
}
